package cn.jantd.modules.activiti.command;

import cn.jantd.modules.activiti.entity.Task;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.IdentityLinkType;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BackTaskCmd implements Command {

	private String taskId;
	private Map<String, Object> variables;

	private List backTaskIds;

	public BackTaskCmd(String taskId, Map<String, Object> variables, List backTaskIds) {
		this.taskId = taskId;
		this.variables = variables;
		this.backTaskIds = backTaskIds;
	}

	public Object execute(CommandContext commandContext) {
		TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
		TaskEntity taskEntity = taskEntityManager.findTaskById(taskId);
		ExecutionEntity executionEntity = taskEntity.getExecution();
		// 设置流程变量
		executionEntity.setVariables(variables);

		// 触发执行监听器complete事件
		taskEntity.fireEvent(TaskListener.EVENTNAME_COMPLETE);

		// 触发全局事件转发器TASK_COMPLETED事件
		if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
			Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder
					.createEntityWithVariablesEvent(ActivitiEventType.TASK_COMPLETED, this, variables, false));
		}

		// 添加act_ru_identitylink表记录。常规流程实例id与执行id相同
		if (Authentication.getAuthenticatedUserId() != null && executionEntity.getProcessInstanceId() != null) {
			executionEntity.involveUser(Authentication.getAuthenticatedUserId(), IdentityLinkType.PARTICIPANT);
		}



		String preActivityId =  executionEntity.getActivity().getIncomingTransitions().get(0).getSource().getId();



		String processDefinitionId = executionEntity.getProcessDefinitionId();
		ProcessDefinitionEntity processDefinitionEntity = Context.getProcessEngineConfiguration().getDeploymentManager()
				.findDeployedProcessDefinitionById(processDefinitionId);
		ActivityImpl desActivity = processDefinitionEntity.findActivity(preActivityId);

		if(backTaskIds.size() < 1){
			if(preActivityId.indexOf("Gateway") != -1 ){
				List list = new ArrayList();
				for (int i= 0;i<desActivity.getIncomingTransitions().size();i++){
					Task task = new Task();
					task.setName(desActivity.getIncomingTransitions().get(i).getSource().getProperty("name").toString());
					task.setId(desActivity.getIncomingTransitions().get(i).getSource().getId());
					task.setNodeType("Gateway");
					list.add(task);
				}
				return list;
			}
		}
		if(backTaskIds.size() > 0){
			for (int i = 0;i<1;i++){
				desActivity = processDefinitionEntity.findActivity(this.backTaskIds.get(0).toString());
				executionEntity.executeActivity(desActivity);
			}
			taskEntityManager.deleteTask(taskEntity, TaskEntity.DELETE_REASON_COMPLETED, false);
			return null;
		}
		Task task = new Task();
		List list = new ArrayList();
		task.setName(desActivity.getProperties().get("name").toString());
		task.setId(desActivity.getId());
		task.setNodeType("Activity");
		list.add(task);
		// 删除任务
//		taskEntityManager.deleteTask(taskEntity, TaskEntity.DELETE_REASON_COMPLETED, false);
//		executionEntity.executeActivity(desActivity);

		return list;
	}
}
